﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SalePartial.BLL;
using System.Web.Security;
using System.Data.SqlClient;
using SalePartial.Model;
using XunPan.Web.Globals;
using SalePartial.Utility;
using System.Text;
using Telerik.Web.UI;

public partial class Login_regPurchases : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            //if (User.Identity.IsAuthenticated)
            //{
            //    Response.Clear();
            //    Response.Redirect(GlobalSetting.UrlHomePage, true);
                
            //}
            showPageFromSession();
            Master.FinshOneProcess(REG_PROCESS.PURCHASE_INFO, REG_STATUS.USED);
        }
    }


    protected void btnUploadPhoto_Click(object sender, System.EventArgs e)
    {
            if (ruploadPhoto.UploadedFiles.Count > 0)
            {


                string oldfilename = ruploadPhoto.UploadedFiles[0].GetName();
                string newfilename = null;
                string oldpath = null;
                string newpath = null;
                Trace.Warn(oldfilename);


                oldpath = Server.MapPath(ruploadPhoto.TargetFolder) + "\\" + oldfilename;

                Trace.Warn(oldpath);


                newfilename = FileUtility.CreateUniqueFileName(oldfilename);
                newpath = Server.MapPath(ruploadPhoto.TargetFolder) + "\\" + newfilename;

                System.IO.File.Move(oldpath, newpath);



                imgPhoto.ImageUrl = ruploadPhoto.TargetFolder + "/" + newfilename;

                //imgPhoto.ImageUrl = ruploadPhoto.TargetFolder + "/Logon_18.jpg";

                btnDeletePhoto.Visible = btnUploadPhoto.Visible;
                btnUploadPhoto.Visible = !btnDeletePhoto.Visible;
                ruploadPhoto.Visible = !btnDeletePhoto.Visible;

        }
    }

    protected void btnDeletePhoto_Click(object sender, System.EventArgs e)
    {
        string filepath = Server.MapPath(imgPhoto.ImageUrl);
        if (!System.IO.Path.GetFileNameWithoutExtension(filepath).Equals("blank_photo"))
        {
            try
            {
                System.IO.File.Delete(filepath);
            }
            catch (Exception ex)
            {
                return;

            }

            imgPhoto.ImageUrl = "~/images/logon/blank_photo.jpeg";

            btnDeletePhoto.Visible = btnUploadPhoto.Visible;
            btnUploadPhoto.Visible = !btnDeletePhoto.Visible;
            ruploadPhoto.Visible = !btnDeletePhoto.Visible;
        }

    }
    protected void btnUploadLogo_Click(object sender, System.EventArgs e)
    {

            if (ruploadLogo.UploadedFiles.Count > 0)
            {
                string oldfilename = ruploadLogo.UploadedFiles[0].GetName();
                string newfilename = null;
                string oldpath = null;
                string newpath = null;
                Trace.Warn(oldfilename);


                oldpath = Server.MapPath(ruploadLogo.TargetFolder) + "\\" + oldfilename;

                Trace.Warn(oldpath);


                newfilename = FileUtility.CreateUniqueFileName(oldfilename);
                newpath = Server.MapPath(ruploadLogo.TargetFolder) + "\\" + newfilename;
   
                System.IO.File.Move(oldpath, newpath);


                imgLogo.ImageUrl = ruploadLogo.TargetFolder + "/" + newfilename;


                btnDeleteLogo.Visible = btnUploadLogo.Visible;
                btnUploadLogo.Visible = !btnDeleteLogo.Visible;
                ruploadLogo.Visible = !btnDeleteLogo.Visible;
            }
    }
    protected void btnDeleteLogo_Click(object sender, System.EventArgs e)
    {
        string filepath = Server.MapPath(imgLogo.ImageUrl);
        if (!System.IO.Path.GetFileNameWithoutExtension(filepath).Equals("blank_logo"))
        {
            try
            {
                System.IO.File.Delete(filepath);
            }
            catch (Exception ex)
            {
                return;

            }

            imgLogo.ImageUrl = "~/images/logon/blank_logo.jpeg";

            btnDeleteLogo.Visible = btnUploadLogo.Visible;
            btnUploadLogo.Visible = !btnDeleteLogo.Visible;
            ruploadLogo.Visible = !btnDeleteLogo.Visible;
        }
    }

    protected void ibtBack_Click(object sender, System.EventArgs e)
    {
        Master.GoBackPreProcess();

        //Page.Response.Redirect("~/Login/RegSupplies.aspx", true);
        string prePage = (string)Session[ConstantSession.PRE_PAGE_ID];
        if (prePage != null)
        {
            Page.Response.Redirect(prePage, true);
        }
        else
        {
            Page.Response.Redirect("~/Login/regPerson.aspx", true);
        }
    }

    protected void ibtSubmit_Click(object sender, System.EventArgs e)
    {
        List<XPCompanyCertInfo> certInfoList =
(List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST];

        if (certInfoList == null || certInfoList.Count == 0)
        {
            //rgridCompanyCerts.Controls.Add(new LiteralControl("您还未添加任何资质认证哦..."));
            return;
        }

        RadCaptchaReg.Validate();
        if (!RadCaptchaReg.IsValid)
        {
            return;
        }

        XPCompanyInfo companyInfo = null;
        XPCompanyCertInfo cert = null;
        if (Session[ConstantSession.REG_PURCH_COMPY_INFO] == null)
        {
            companyInfo = new XPCompanyInfo();
        }
        else
        {
            companyInfo = (XPCompanyInfo)Session[ConstantSession.REG_PURCH_COMPY_INFO];
        }

        if (Session[ConstantSession.REG_PURCH_COMPYCERT_INFO] == null)
        {
            cert = new XPCompanyCertInfo();  
        }
        else
        {
            cert =  (XPCompanyCertInfo)Session[ConstantSession.REG_PURCH_COMPYCERT_INFO];
        }

        var _with3 = companyInfo;

        _with3.Photo = GlobalUtility.ResolveAppRelativeVirtualPath(imgPhoto.ImageUrl);
        _with3.Logo = GlobalUtility.ResolveAppRelativeVirtualPath(imgLogo.ImageUrl);
        _with3.Monetary = rcbCurrency.SelectedValue;
        _with3.Description = tbDescription.Text;

        //????
        _with3.BuyerModerateStatus = 0;
        //创建企业标识

        _with3.CompanyName = tbCompanyName.Text.Trim();
        _with3.CompanyAliasName = _with3.CompanyName;
        _with3.Industry = rcbIndustry.SelectedItem.Text;

        _with3.WebSite = rtbWebsite.Text.Trim();
        _with3.Fund = rntbFund.Value.ToString();

        _with3.OfficePhone = tbPhone.Text;
        _with3.CellPhone = tbCellphone.Text;
        _with3.Fax = tbFax.Text.Trim();

        _with3.Scale = rblFirmSize.SelectedItem.Text;
        //职位=CompanyOwner?????
        _with3.CompanyOwner = rcbJobtitle.SelectedItem.Text;
        _with3.Photo = imgPhoto.ImageUrl;
        _with3.Logo = imgLogo.ImageUrl ;
        _with3.IsCellPhonePublic = cbCellphone.Checked;
        _with3.IsOfficePhonePublic = cbPhone.Checked;
        _with3.IsFaxPublic = cbFax.Checked;
        _with3.IsEmailPublic = false;

       

        var _with4 = cert;
        //_with4.CompanyID = company.CompanyID;
        //_with4.CreateUserID = company.UserID;

        _with4.CertName = tbLicense.Text;
        _with4.CertType = 0;
        _with4.CertFileName = lnkLicense.Text;
        _with4.CertFileContentType = btnUploadLicense.CommandName;
        try
        {
            _with4.CertFileSize = Convert.ToInt32(btnUploadLicense.CommandArgument);
        }
        catch
        {
            _with4.CertFileSize = 0;
        }

        if (lnkLicense.Text.Trim() != string.Empty)
        {
            //_with4.CertFileData = System.IO.File.ReadAllBytes(Server.MapPath(lnkLicense.NavigateUrl));
            _with4.CertFileData =
                Encoding.Unicode.GetBytes(lnkLicense.NavigateUrl);
        }

        Session[ConstantSession.REG_PURCH_COMPY_INFO] = companyInfo;
        Session[ConstantSession.REG_PURCH_COMPYCERT_INFO] = cert;

        Session[ConstantSession.PRE_PAGE_ID] = Request.FilePath;

        Page.Response.Redirect("~/Login/regConfirm.aspx", true);

    }

    protected void btnUploadLicense_Click(object sender, System.EventArgs e)
    {

            if (ruploadLicense.UploadedFiles.Count > 0)
            {
                string oldfilename = ruploadLicense.UploadedFiles[0].GetName();
                string newfilename = null;
                string oldpath = null;
                string newpath = null;
                Trace.Warn(oldfilename);


                oldpath = Server.MapPath(ruploadLicense.TargetFolder) + "\\" + oldfilename;


                newfilename = FileUtility.CreateUniqueFileName(oldfilename);
                newpath = Server.MapPath(ruploadLicense.TargetFolder) + "\\" + newfilename;

                System.IO.File.Move(oldpath, newpath);



                lnkLicense.Text = oldfilename;
                lnkLicense.NavigateUrl = ruploadLicense.TargetFolder + "/" + newfilename;

                //将License文件的大小和类型信息存入btn中
                btnUploadLicense.CommandName = ruploadLicense.UploadedFiles[0].ContentType;
                btnUploadLicense.CommandArgument = ruploadLicense.UploadedFiles[0].ContentLength.ToString();


                lnkLicense.Visible = btnUploadLicense.Visible;
                btnDeleteLicense.Visible = btnUploadLicense.Visible;
                btnUploadLicense.Visible = !btnDeleteLicense.Visible;
                ruploadLicense.Visible = !btnDeleteLicense.Visible;
            }
        
    }

    protected void btnDeleteLicense_Click(object sender, System.EventArgs e)
    {
        string filepath = Server.MapPath(lnkLicense.NavigateUrl);

        System.IO.File.Delete(filepath);

        lnkLicense.Visible = btnUploadLicense.Visible;
        btnDeleteLicense.Visible = btnUploadLicense.Visible;
        btnUploadLicense.Visible = !btnDeleteLicense.Visible;
        ruploadLicense.Visible = !btnDeleteLicense.Visible;

    }


    private Boolean showPageFromSession()
    {
        XPCompanyInfo newcompany = (XPCompanyInfo)Session[ConstantSession.REG_PURCH_COMPY_INFO];

        if (newcompany == null)
        {
            newcompany = (XPCompanyInfo)Session[ConstantSession.REG_SUPPLY_COMPY_INFO];
        }
        if (newcompany != null)
        {
            tbCompanyName.Text = newcompany.CompanyName;
            
            foreach (RadComboBoxItem item in rcbIndustry.Items)
            {
                if (item.Text == newcompany.Industry)
                {
                    rcbIndustry.SelectedValue = item.Value;
                    break;
                }
            }

            rtbWebsite.Text = newcompany.Fund;
            tbPhone.Text = newcompany.OfficePhone;
            tbCellphone.Text = newcompany.CellPhone;
            tbFax.Text = newcompany.Fax;
            imgPhoto.ImageUrl = newcompany.Photo;
            imgLogo.ImageUrl = newcompany.Logo;
            rcbCurrency.Text = newcompany.Monetary;
            tbDescription.Text = newcompany.Description;
            cbCellphone.Checked = newcompany.IsCellPhonePublic;
            cbPhone.Checked = newcompany.IsOfficePhonePublic;
            cbFax.Checked = newcompany.IsFaxPublic;

            rntbFund.Text = newcompany.Fund;

            foreach (ListItem item in rblFirmSize.Items)
            {
                if (item.Text == newcompany.Scale)
                {
                    rblFirmSize.SelectedValue = item.Value;
                    break;
                }
            }

            foreach (RadComboBoxItem item in rcbJobtitle.Items)
            {
                if (item.Text == newcompany.CompanyOwner)
                {
                    rcbJobtitle.SelectedValue = item.Value;
                    break;
                }
            }

        }

        XPCompanyCertInfo cert = (XPCompanyCertInfo)Session[ConstantSession.REG_PURCH_COMPYCERT_INFO];
        if (cert == null)
        {
            cert = (XPCompanyCertInfo)Session[ConstantSession.REG_SUPPLY_COMPYCERT_INFO];
        }
        if (cert != null)
        {
            tbLicense.Text = cert.CertName;
            if (cert.CertFileData != null)
            {
                lnkLicense.Visible = true;
                btnDeleteLicense.Visible = true;
                btnUploadLicense.Visible = false;
                ruploadLicense.Visible = false;

                lnkLicense.Text = cert.CertFileName;
                lnkLicense.NavigateUrl = Encoding.Unicode.GetString(cert.CertFileData);
            }
        }


        if (Session[ConstantSession.REG_PURCH_COMPYCERT_LIST] == null)
        {
            Session[ConstantSession.REG_PURCH_COMPYCERT_LIST] = new List<XPCompanyCertInfo>();

        }

        //if (Session[ConstantSession.REG_PURCH_COMPYCERT_LIST] == null)
        //{
        //    Session[ConstantSession.REG_PURCH_COMPYCERT_LIST] = Session[ConstantSession.REG_SUPPLY_COMPYCERT_LIST];
        //}

        rgridCompanyCerts.DataSource = (List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST];
        rgridCompanyCerts.DataBind();

        return true;
    }

    protected void rgridCompanyCerts_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        //string certID = ((GridDataItem)e.Item).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CertID"].ToString();

        List<XPCompanyCertInfo> certLists = (List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST];
        if (((List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST]).Count < e.Item.ItemIndex)
        {
            rgridCompanyCerts.Controls.Add(new LiteralControl("Unable to delete cert. Reason: "));
            return;
        }
        ((List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST]).RemoveAt(e.Item.ItemIndex);


        //XPCompanyCertInfo cert = default(XPCompanyCertInfo);
        //XPCompanyCert bilCorpcert = new XPCompanyCert();
        //try
        //{
        //    cert = bilCorpcert.GetXPCompanyCert(new Guid(certID));
        //    bilCorpcert.Delete(cert);

        //}
        //catch (Exception ex)
        //{
        //    rgridCompanyCerts.Controls.Add(new LiteralControl("Unable to delete cert. Reason: " + ex.Message));
        //    e.Canceled = true;
        //}

    }

    protected void rgridCompanyCerts_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        GridEditableItem editedItem = (GridEditableItem)e.Item;
        GridEditManager editMan = editedItem.EditManager;

        RadAsyncUpload upload = (RadAsyncUpload)editMan.GetColumnEditor("CertFileName").ContainerControl.FindControl("radUploadCert");

            string filename = upload.UploadedFiles[0].GetName();
            string filepath = null;
            filepath = Server.MapPath(upload.TargetFolder) + "\\" + filename;

            XPCompanyCertInfo cert = new XPCompanyCertInfo();
            XPCompanyCert bilCorpcert = new XPCompanyCert();
            var _with6 = cert;
            //_with6.CompanyID = new Guid(hfRegedCompany.Value);
            //_with6.CreateUserID = new XPCompany().GetXPCompany(_with6.CompanyID).UserID;

            _with6.CertName = ((GridDropDownColumnEditor)editMan.GetColumnEditor("CertName")).SelectedText;
            _with6.CertType = 1;
            _with6.CertFileName = filename;
            _with6.CertFileContentType = upload.UploadedFiles[0].ContentType;
            _with6.CertFileSize = upload.UploadedFiles[0].ContentLength;

            if (System.IO.File.Exists(filepath))
            {
                _with6.CertFileData = System.IO.File.ReadAllBytes(filepath);
            }


            _with6.CertID = new Guid();
            ((List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST]).Add(_with6);

            rgridCompanyCerts.DataSource = ((List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST]);
            rgridCompanyCerts.DataBind();

            //try
            //{
            //    bilCorpcert.Insert(_with6);
            //    System.IO.File.Delete(filepath);

            //}
            //catch (Exception ex)
            //{
            //    rgridCompanyCerts.Controls.Add(new LiteralControl("Unable to insert into certs. Reason: " + ex.Message));
            //    e.Canceled = true;
            //}

    }

    protected void rgridCompanyCerts_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {

        rgridCompanyCerts.DataSource = (List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST];
        //rgridCompanyCerts.DataBind();

        if (e.CommandName == "InitInsert" || e.CommandName == "PerformInsert")
        {
            //if (bilCorpcert.SelectByCompanyID(new Guid(hfRegedCompany.Value)).Tables[0].Rows.Count >= GlobalSetting.MaxCompanyCertsQuantity)
            if (((List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST]).Count >= GlobalSetting.MaxCompanyCertsQuantity)
            {
                rgridCompanyCerts.Controls.Add(new LiteralControl("您上传的认证数目已达最大."));
                e.Canceled = true;
                return;
            }
        }
        else if (e.CommandName == "DownloadCert")
        {
            //string certID = ((GridDataItem)e.Item).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CertID"].ToString();
            XPCompanyCertInfo cert = default(XPCompanyCertInfo);
            try
            {
                cert = ((List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST])[e.Item.ItemIndex];

                //cert = bilCorpcert.GetXPCompanyCert(new Guid(certID));
                var _with7 = cert;
                string fileName = _with7.CertFileName;
                int fileSize = _with7.CertFileSize;
                Context.Server.ScriptTimeout = 600;
                Context.Response.Buffer = true;
                Context.Response.Clear();
                Context.Response.ContentType = _with7.CertFileContentType;
                Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
                Context.Response.AddHeader("Content-Length", fileSize.ToString());
                byte[] fileBuffer = new byte[fileSize + 2];
                // buffer of the file data

                Context.Response.BinaryWrite(_with7.CertFileData);

                // End the response
                Context.Response.End();
            }
            catch (Exception ex)
            {
                rgridCompanyCerts.Controls.Add(new LiteralControl("Unable to get cert. Reason: " + ex.Message));
                e.Canceled = true;
            }

        }
    }


    private List<XPCompanyCertInfo> CertItems
    {
        get
        {
            List<XPCompanyCertInfo> certs = (List<XPCompanyCertInfo>)Session[ConstantSession.REG_PURCH_COMPYCERT_LIST];
            if ((certs == null))
            {
                certs = new List<XPCompanyCertInfo>();
                Session[ConstantSession.REG_PURCH_COMPYCERT_LIST] = certs;
            }
            return certs;
        }
    }



}